/*
test call:
get("http://example.com",alert);
*/

/*
Element.implement({
    append: function(newhtml)
        return this.adopt(new Element('div', {html: newhtml}).getChildren());
    }
});
*/

var regTemplate = {"firstName":"Reg",
    "lastName":"Ata",
    "companyName":"Test Company",
    //"email":"",
    //"contactNumber":"",
    "password":"121212",
    "passwordAgain":"121212",
    "secretRequestAnswer":"Rylsk",
    "contactNumber": "+1 (650) "+getRandomInt(1000000,999999),
    "squestion": "11"
    //"secretRequestQuestionId": "11"
//"use_no_answer":"off"
};

var rcConfigForm = '<div id="rc-regata-form"><div class="field"><label for="email">E-mail</label><input type="text" id="regata-email" name="email" /></div>'+
'<div id="rc-regata-next" style="top:50px;"><a href="javascript:;">MAGIC! >></a></div></div>';

function testRegata(){
    //debugger;
    var number = $$("#numberList .active td")[1];
	var email=$("regata-email").get('value');
    if (email){
        localStorage['email'] = email;
        localStorage['number'] = number.get('text').replace(/\D/g,"");
        $("sendToPlan").onclick();
    }
    else{
        alert('Введите почту!');
    }
}

function getBase64Image(img) {
    // Create an empty canvas element
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    // Get the data-URL formatted image
    // Firefox supports PNG and JPEG. You could check img.src to
    // guess the original format, but be aware the using "image/jpg"
    // will re-encode the image.
    var dataURL = canvas.toDataURL("image/png");

    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

function sendCaptchaToDecode(){
	var canvas =  getBase64Image(document.getElementById("captcha"));
    var container = $$("body")[0];
    new Request.HTML({
    	data: {'canvas':canvas},
        url: 'http://ncplus/decaptcha.php', 
        onSuccess: function(html) { // запрос выполнен уcпешно
            
        	console.log(html); 
        },
        onFailure: function() { // ошибка запроса
            container.set('html', 'The request failed.');
        },
        onCancel: function() { // отмена запроса
            container.set('html', 'The request calcelled.');
        }
    }).send();
}

function get_cookies_array() {
    var cookies = { };
    if (document.cookie && document.cookie != '') {
        var split = document.cookie.split(';');
        for (var i = 0; i < split.length; i++) {
            var name_value = split[i].split("=");
            name_value[0] = name_value[0].replace(/^ /, '');
            var name = decodeURIComponent(name_value[0]);
            var value = decodeURIComponent(name_value[1]);
            cookies[name] = value;
        }
    }
    return cookies;
}


function get(url, callback) {    

    chrome.extension.sendRequest({'action' : 'xget', 'url':url}, callback);

};

function currStep(){
    return 'selectNumber';
}

function getRandomInt(min,max){
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

setTimeout(main,100);
function main(){
switch(location.pathname){
    case '/ordernow/number-select.html':
        number_select();
    break;
    case '/ordernow/upgrade-to-office.html':
        if (typeof localStorage['number'] != "undefined"){
            var numberHTML = '<b>processing '+localStorage['number']+'</b>';
            $$("body")[0].adopt(new Element('div', {html: numberHTML}).getChildren());
            $("confirm_no").onclick();
        }
    break;
    case '/signup/contact-information.html':
        var allInputs = {};
        $$("#contentSignup_bg input").each(function(el){
            if (regTemplate[el.get('name')])
                el.set('value',regTemplate[el.get('name')])
            //allInputs[el.get('name')] = el.get('value');
        })
        /*
        TODO
        get email from localStorage of domain www.ringcentral.com
         */
        var email = 'denis.obydennykh+'+getRandomInt(100000,99999999999)+'@dins.ru';
        sendCaptchaToDecode();
        $("squestion").set('value',regTemplate.squestion);
        $("email").set('value',email);
        $("policyagree").set("checked","checked");
    break;
    case '/test.html':
    	sendCaptchaToDecode();
    break;
}
}

function number_select(){
    setTimeout(function(){
        //debugger;
        $$("body")[0].adopt(new Element('div', {html: rcConfigForm}).getChildren());
        $("rc-regata-next").onclick = testRegata;
        if (localStorage['email'])
            $("regata-email").set('value',localStorage['email']);
        //var number = $$("#numberList .active td")[1];
        setTimeout(function(){
            //var number = $$("#numberList #parentContent>div")[5];
            //number.fireEvent("click");
            //number.onclick();
            //$$("#sendToPlan a")[0].set('text','MAGIC!');
            //$$("#sendToPlan")[0].hide();
            //document.getElementById("sendToPlan").innerHTML = "<a>test</a>";
        },1000);
    },1000);
}